package com.sywb.chuangyebao.contract;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.MyUpdateService;
import com.sywb.chuangyebao.bean.DistrictConvert;
import com.sywb.chuangyebao.bean.DistrictInfo;
import com.sywb.chuangyebao.bean.UserInfo;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.view.NewsDetailActivity;
import com.sywb.chuangyebao.view.QAndADetailActivity;
import com.sywb.chuangyebao.view.TopicActivity;
import com.sywb.chuangyebao.view.TrainMediaDetailActivity;
import com.sywb.chuangyebao.view.UserMessageActivity;
import com.sywb.chuangyebao.view.VideoDetailActivity;
import com.sywb.chuangyebao.view.WebActivity;

import org.bining.footstone.db.DbManager;
import org.bining.footstone.log.Logger;
import org.bining.footstone.mvp.IView;
import org.bining.footstone.presenter.BasePresenter;
import org.bining.footstone.presenter.PermissionsPresenter;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.SharedUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public interface MainContract {

    interface View extends IView {

        /**
         * 是否有新消息
         */
        void hasNews(boolean isNews);
    }

    class Presenter extends PermissionsPresenter<View> {

        @Override
        public void onStart() {
            initDistrict();

            questPermissions(new String[]{Manifest.permission.READ_PHONE_STATE});
        }

        private void initDistrict() {
            long count = DbManager.getInstance().queryCount(DistrictInfo.class);
            if (count < 1) {
                try {
                    InputStreamReader isr = new InputStreamReader(mActivity.getAssets().open("district.json"), "UTF-8");
                    BufferedReader br = new BufferedReader(isr);
                    String line;
                    StringBuilder builder = new StringBuilder();
                    while ((line = br.readLine()) != null) {
                        builder.append(line.trim());
                    }
                    br.close();
                    isr.close();

                    LinkedHashMap<String, DistrictConvert> params = JSON.parseObject(builder.toString(), new TypeReference<LinkedHashMap<String, DistrictConvert>>() {
                    });

                    List<DistrictInfo> districtInfos = new ArrayList<>();
                    for (Map.Entry<String, DistrictConvert> provinceEntry : params.entrySet()) {
                        DistrictConvert provinceOld = provinceEntry.getValue();

                        DistrictInfo province = new DistrictInfo();
                        province.id = provinceEntry.getKey();
                        province.name = provinceOld.name;
                        province.code = provinceOld.code;
                        province.parentId = "0";
                        province.postalCode = "null";

                        districtInfos.add(province);

                        if (provinceOld.cell != null && provinceOld.cell.size() > 0) {
                            for (Map.Entry<String, DistrictConvert> cityEntry : provinceOld.cell.entrySet()) {
                                DistrictConvert cityOld = cityEntry.getValue();

                                DistrictInfo city = new DistrictInfo();
                                city.id = cityEntry.getKey();
                                city.name = cityOld.name;
                                city.code = cityOld.code;
                                city.parentId = province.id;
                                city.postalCode = cityOld.zip;

                                districtInfos.add(city);

                                if (cityOld.cell != null && cityOld.cell.size() > 0) {
                                    for (Map.Entry<String, DistrictConvert> areaEntry : cityOld.cell.entrySet()) {
                                        DistrictConvert areaOld = areaEntry.getValue();

                                        DistrictInfo area = new DistrictInfo();
                                        area.id = areaEntry.getKey();
                                        area.name = areaOld.name;
                                        area.code = areaOld.code;
                                        area.parentId = city.id;
                                        area.postalCode = areaOld.zip;

                                        districtInfos.add(area);
                                    }
                                }
                            }
                        }
                    }

                    Logger.e("DistrictInfo：" + JSON.toJSONString(districtInfos));

                    DbManager.getInstance().save(districtInfos);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onPermissionsSuccess(String[] strings) {
            checkVersion();
        }

        @Override
        public void onPermissionsFailure(String strMsg) {
            super.onPermissionsFailure(strMsg);
            checkVersion();
        }

        private void checkVersion() {
            mActivity.startService(new Intent(mContext, MyUpdateService.class));
        }

        private void initFileConfig() {
            HttpUtils.getFileConfig(new HttpCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    Logger.e("getFileConfig" + s);
                    SharedUtils.put(Constants.USERFILECONFIG, s);
                }
            });
        }

        public void aliViewJump() {
            // 主题Type》》article:文章详情页 video:视频详情页 wenda 问答详情页 topic 话题聚合页 video_train 培训视频详情页 article_train 培训文章详情页
            // url 指定链接地址 notice 公告 chuangtv 创TV project 项目  notifi 通知  Reservation 创TV预约
            String extraMap = SharedUtils.getString(Constants.USERMESSAGERECEIVER, "");
            if (!TextUtils.isEmpty(extraMap)) {
                SharedUtils.put(Constants.USERMESSAGERECEIVER, "");
                Map<String, String> map = JSON.parseObject(extraMap, new TypeReference<Map<String, String>>() {
                });

                if (mView == null || !map.containsKey("topic_type")) {
                    return;
                }

                String type = map.get("topic_type");
                String data = map.get("topic_id");

                switch (type) {
                    case "article":// 文章详情页
                        mView.advance(NewsDetailActivity.class, Integer.parseInt(data));
                        break;
                    case "video":// 视频详情页
                        mView.advance(VideoDetailActivity.class, Integer.parseInt(data));
                        break;
                    case "wenda":// 问答详情页
                        mView.advance(QAndADetailActivity.class, Integer.parseInt(data));
                        break;
                    case "topic":// 话题聚合页
                        mView.advance(TopicActivity.class, Integer.parseInt(data));
                        break;
                    case "video_train":// 培训视频详情页
                        mView.advance(TrainMediaDetailActivity.class, "视频详情", data);
                        break;
                    case "article_train":// 培训文章详情页
                        mView.advance(TrainMediaDetailActivity.class, "专题详情", data);
                        break;
                    case "url":// 指定链接地址
                        mView.advance(WebActivity.class, "", data);
                        break;
                    case "project":// 项目
                        break;
                    case "chuangTv":
                        RxBus.get().post("goBusinessTV", extraMap);
                        break;
                    case "reservation": // 创TV预约
                        RxBus.get().post("goBusinessTV", extraMap);
                        break;
                    case "notifi":
                        if (SharedUtils.getBoolean(Constants.USERISLOGIN, false)) {
                            mView.advance(UserMessageActivity.class, "", 0);
                        }
                        break;
                    case "notice":
                        if (SharedUtils.getBoolean(Constants.USERISLOGIN, false)) {
                            mView.advance(UserMessageActivity.class, "", 2, data);
                        }
                        break;
                }
            }
        }

    }
}
